package com.edu.whty.controller;

import com.edu.whty.common.constants.CodeConstants;
import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.HttpClientUtil;
import com.edu.whty.common.tools.SysConfig;
import com.edu.whty.common.tools.TeaHelpUtils;
import com.edu.whty.common.tools.redis.RedisUtil;
import com.edu.whty.entity.base.ResponseEntity;
import com.edu.whty.entity.usertextbook.TbUserTextbookChapter;
import com.edu.whty.service.UserTextBookService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/resource")
public class ResourceController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserTextBookService userTextBookService;

    @Autowired
	private RedisUtil redisUtil;

    private static String TYPE = "1";//多平台查询
    private static String KEY_PREFIX = "resource";
	private static String SEPARATOR = "|";
	private static String BOOK_TYPE = "1";//自定义数据查询
	private static String CMS_PLATFORM_CODE = "111111";

    @RequestMapping(value = "/queryChapters", method = RequestMethod.POST)
    public ResponseEntity queryChapters(HttpServletRequest request, HttpServletResponse response, @RequestBody String body) {
        try {
            if (logger.isInfoEnabled()) {
                logger.info("根据教材ID或者章节上级ID查询章节信息接口调用，参数：" + body);
            }

            checkParam(body);
            String netIp = null == request.getAttribute("netIp") ? null : request.getAttribute("netIp").toString();
            JSONObject reqJson = JSONObject.fromObject(body);
			String textbookId = reqJson.optString("textbookId");
            String chapterPId = reqJson.optString("chapterPId");
            String id = reqJson.optString("id");
            String orgId = reqJson.optString("orgId");
            String status = reqJson.optString("status");

            Map<String, Object> param = new HashMap<String, Object>();
            List<TbUserTextbookChapter> chapterList = null;
			param.put("textbookId", textbookId);
			param.put("chapterPId", chapterPId);
			param.put("id", id);
			param.put("orgId", orgId);
			param.put("status", status);
			chapterList = userTextBookService.loadUserTextBookChapter(param);

			return ResponseEntity.getSuccessResponse(chapterList);
        } catch (Exception e) {
            logger.error("cms error url=" + SysConfig.getStrValue(TeaHelpUtils.QUERY_CHAPTERS) + "&param=" + body);
            logger.error(e.getMessage());
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "查询编目信息异常");
        }
    }

    private String checkParam(String body) throws Exception {
        JSONObject reqJson = null;
        reqJson = JSONObject.fromObject((body == null || body.equals("")) ? "{}" : body);
        //参数检验
        if (!this.isNotNull(reqJson)) {
            throw new Exception("参数不存在");
        }
        return reqJson.toString();
    }

    /**
	 * 查询返回对应url
	 * @param body
	 * @param request
	 * @param url
	 * @return
	 */
	private String getUrl(String body,HttpServletRequest request,String url){
		String urlRet = "";
		if(body!=null && !body.equals("")){
			JSONObject reqJson = JSONObject.fromObject(body);
			String type  = reqJson.optString("type");//表示根据多平台查询

	        if(StringUtils.isNotEmpty(type) && TYPE.equals(type)){
	        	urlRet  = SysConfig.getStrValue(url);
	        }else{
	        	String loginPlatformCode = (String)request.getAttribute("loginPlatformCode");
	        	urlRet  = SysConfig.getStrValue(url,loginPlatformCode);
	        	String cmsGatewayUrl = SysConfig.getStrValue("cms_gateway_url_888888");
	        	//从System.properties文件获取慧教云cms-gateway内网地址
	        	if(null!=urlRet&&StringUtils.isNotEmpty(urlRet)
	        			&&null!=cmsGatewayUrl&&StringUtils.isNotEmpty(cmsGatewayUrl)){
	        		urlRet = urlRet.replace("http://cms-gateway.huijiaoyun.com", cmsGatewayUrl);
	        	}
	        }
		}
		return urlRet;
	}

	/*
	 * 缓存取数据
	 */
	private String getFromCache(String key,String url,JSONObject reqJson,String netIp) throws Exception {
		String val = (String) redisUtil.get(key);
		String resp = "";
		if(StringUtils.isEmpty(val) ||  StringUtils.isEmpty(key)){
			long start = System.currentTimeMillis();

		    //平台编码转换
//			if(reqJson.get("platformCode")!=null){
//				reqJson.element("platformCode", "888888");
//			}
//			if(reqJson.get("platformCode")!=null && "320585".equals(reqJson.get("platformCode").toString().trim())){
//				reqJson.element("platformCode", reqJson.get("platformCode"));
//			}else{
//				reqJson.element("platformCode", "888888");
//			}

			//教材数据统一去实体平台的2.7.0版本开始
			//String loginPlatformCode = reqJson.optString("loginPlatformCode")==null?"888888":reqJson.optString("loginPlatformCode");
			//reqJson.put("platformCode", loginPlatformCode);

			//教材章节信息默认用111111平台编码对应的教材章节信息   2020/3/25
			reqJson.put("platformCode", "111111");
			reqJson.put("loginPlatformCode", "111111");
//			reqJson.element("platformCode", SysConfig.getStrValue("platformCode")==null?"888888":SysConfig.getStrValue("platformCode"));
			String paramStr = reqJson.toString();
			logger.info("url==="+url+"&param===="+paramStr);
			resp= HttpClientUtil.post(url,paramStr,netIp);
			long end = System.currentTimeMillis();
			if(end-start>Constant.TIME){
				logger.error("cms long time  error: 接口请求url="+url+"&param="+paramStr+"&time="+(end-start));
			}else{
				logger.info("cms time : 接口请求url="+url+"&param="+paramStr+"&time="+(end-start));
			}
			if(StringUtils.isNotEmpty(resp)){
				com.alibaba.fastjson.JSONObject resultObj = com.alibaba.fastjson.JSONObject.parseObject(resp);
				if("000000".equals(resultObj.getString("result")) ){
					redisUtil.set(key, resp, Constant.REDIS_DEFAULT_EXPIRES);
				}
			}
		}else{
			if (logger.isInfoEnabled()) {
				logger.info("缓存获取 key：" +key+" value 值："+ resp);
			}
			resp = val;
		}
		return resp;
	}

	private String getKeyQueryChapters(JSONObject reqJson){
		StringBuffer sb = new StringBuffer();
		if(reqJson!=null && !reqJson.equals("")){
			sb.append(KEY_PREFIX).append(SEPARATOR).append("queryChapters").append(SEPARATOR)
			.append(SEPARATOR).append(CMS_PLATFORM_CODE)
			.append(reqJson.getString("parentType"))
			.append(SEPARATOR).append(reqJson.optString("parentId"))
			.append(SEPARATOR).append(reqJson.optString("retType"));
		}
		return sb.toString();
	}

	/**
	 * 判断对象是否为空
	 *
	 * @param o
	 * @return
	 */
	public boolean isNotNull(Object o) {
		if (o == null) {
			return false;
		} else if (o instanceof String && "".equals(((String) o).trim())) {
			return false;
		} else {
			return true;
		}
	}
}
